<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品名称" prop="storeName">
        <el-input
          v-model="queryParams.storeName"
          placeholder="请输入商品名称/关键字"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="分类" prop="cateId">
        <el-select clearable v-model="queryParams.cateName" class="select-unitName select-option-father"
                   popper-class="select_report_and_type" :popper-append-to-body="false" ref="elSelectTable"
                   @clear="clearOptionTree">
          <el-option class="selectOptionTree" :value="treeNode.label">
            <el-tree
              class="option-tree"
              :data="treeData"
              node-key="value"
              :props="defaultProps"
              :default-expanded-keys="treeExpandedId"
              ref="unitTree"
              highlight-current
              :expand-on-click-node='false'
              @node-click="handleNodeClick"
            >
            </el-tree>
          </el-option>
        </el-select>

      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['custom:product:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['custom:product:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['custom:product:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['custom:product:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="productList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="商品ID" align="center" prop="id"/>
      <el-table-column label="商品图片" align="center" prop="image" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.image" :width="25" :height="25"/>
        </template>
      </el-table-column>
      <el-table-column label="商品名称" align="center" prop="storeName"/>

      <el-table-column label="商品类型" align="center" prop="cateId" width="100">
        <template slot-scope="scope">
          {{scope.row.isVirtual === 0 ? '普通商品' : '其他商品'}}
        </template>
      </el-table-column>
      <el-table-column label="商品售价" align="center" prop="price">
        <template slot-scope="scope">
          {{scope.row.storeProductAttrValueList[0].price == '' ? '' : scope.row.storeProductAttrValueList[0].price}}
        </template>
      </el-table-column>
      <el-table-column label="销量" align="center" prop="sales">
        <template slot-scope="scope">
          {{scope.row.storeProductAttrValueList | salesSum}}
        </template>
      </el-table-column>
      <el-table-column label="库存" align="center" prop="stock">
        <template slot-scope="scope">
          {{scope.row.storeProductAttrValueList | stockSum}}
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="sort">
        <template slot-scope="scope">
          {{scope.row.sort}}
        </template>
      </el-table-column>
      <el-table-column label="商品状态" align="center" prop="isShow">
        <template slot-scope="scope">
          <span v-if="scope.row.isShow === 0" style="color: red">
            未上架
          </span>
          <span v-else style="color: green">
            已上架
          </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['custom:product:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['custom:product:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body :close-on-click-modal="false">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="基础信息" name="first">
          <el-form ref="form" :model="form" :rules="rules" label-width="120px">
            <el-form-item label="商品类型">
              <el-radio-group v-model="form.isVirtual">
                <el-tooltip effect="dark" content="物流发货" placement="top">
                  <el-radio checked border :label="0">普通商品</el-radio>
                </el-tooltip>
                <!--                <el-tooltip effect="dark" content="自动发货" placement="top">-->
                <!--                  <el-radio border :label="1">卡密/网盘</el-radio>-->
                <!--                </el-tooltip>-->
                <!--                <el-tooltip effect="dark" content="自动发货" placement="top">-->
                <!--                  <el-radio border :label="2">优惠券</el-radio>-->
                <!--                </el-tooltip>-->
                <!--                <el-tooltip effect="dark" content="虚拟发货" placement="top">-->
                <!--                  <el-radio border :label="3">虚拟商品</el-radio>-->
                <!--                </el-tooltip>-->
              </el-radio-group>
            </el-form-item>

            <el-form-item label="商品分类" prop="cateId">
              <el-select style="width: 50%" clearable filterable v-model="form.cateId"
                         placeholder="请选择">
                <el-option
                  v-for="item in treeSelectData"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                  :disabled="item.disabled">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="商品名称" prop="storeName">
              <el-input v-model="form.storeName" placeholder="请输入商品名称"/>
            </el-form-item>
            <el-form-item label="单位名" prop="unitName">
              <el-input v-model="form.unitName" placeholder="请输入单位名 （件）"/>
            </el-form-item>
            <el-form-item label="轮播图" prop="sliderImage">
              <image-upload v-model="form.sliderImage"/>
            </el-form-item>
            <!--            <el-form-item label="添加视频" prop="addVideoLink">-->
            <!--              <el-tooltip :content="videoLinkSwitch ? '打开' : '关闭'" placement="top">-->
            <!--                <el-switch-->
            <!--                  v-model="videoLinkSwitch"-->
            <!--                  active-color="#13ce66"-->
            <!--                  :active-value="true"-->
            <!--                  :inactive-value="false">-->
            <!--                </el-switch>-->
            <!--              </el-tooltip>-->
            <!--            </el-form-item>-->
            <!--            <el-form-item v-if="videoLinkSwitch" label="上传视频" prop="videoLink">-->
            <!--              <image-upload :limit="1" v-model="form.videoLink"/>-->
            <!--            </el-form-item>-->
            <el-form-item label="状态" prop="isShow">
              <el-radio v-model="form.isShow" :label="1">上架</el-radio>
              <el-radio v-model="form.isShow" :label="0">下架</el-radio>
            </el-form-item>
            <div class="dialog-footer">
              <el-button type="primary" style="margin-left: 30%" @click="toNext">下一步</el-button>
            </div>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="规格库存" name="second">
          <el-form ref="form" :model="form" :rules="rules" label-width="120px">
            <el-form-item label="商品规格" prop="specs">
              <el-radio v-model="specs" :label="0">单规格</el-radio>
              <el-radio v-model="specs" :label="1">多规格</el-radio>
            </el-form-item>

            <div v-show="specs === 0">
              <el-form-item label="图片" prop="image">
                <image-upload v-model="form.image"/>
              </el-form-item>
              <el-form-item label="成本价" prop="cost">
                <el-input v-model="form.cost" placeholder="请输入成本价"/>
              </el-form-item>
              <el-form-item label="原价" prop="otPrice">
                <el-input v-model="form.otPrice" placeholder="请输入原价"/>
              </el-form-item>
              <el-form-item label="售价" prop="price">
                <el-input v-model="form.price" placeholder="请输入商品售价"/>
              </el-form-item>
              <el-form-item label="库存" prop="stock">
                <el-input type="number" v-model="form.stock" placeholder="库存"/>
              </el-form-item>
              <el-form-item label="商品编号" prop="itemNo">
                <el-input v-model="form.itemNo" placeholder="商品编号"/>
              </el-form-item>
              <el-form-item label="重量（KG）" prop="weight">
                <el-input type="number" v-model="form.weight" placeholder="重量"/>
              </el-form-item>
              <el-form-item label="体积(m³)" prop="volume">
                <el-input type="number" v-model="form.volume" placeholder="体积"/>
              </el-form-item>
            </div>

            <div v-show="specs === 1">
              <el-form-item label="商品规格">
                <el-select @change="selectChange" clearable filterable v-model="form.rule"
                           placeholder="请选择">
                  <el-option
                    v-for="item in ruleSelectList"
                    :key="item.id"
                    :label="item.ruleName"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
                <el-button type="primary" @click="toGenerate">立即生成</el-button>
                <br><br>
                <div class="tag1" v-for="(tag, index) in ruleValue">
                  <el-tag
                    :key="tag.key"
                    effect="dark">
                    {{ tag.key }}
                  </el-tag>
                  <br>
                  <el-tag v-if="tag.value !== ''" v-for="(t, idx) in tag.value.split(',')"
                          :key="t">
                    {{ t }}
                  </el-tag>
                </div>
              </el-form-item>


              <!--              批量设置-->
              <div v-if="isShowTable">
                <el-table border :data="batchObj">
                  <el-table-column label="批量添加">
                    <el-table-column label="图片" align="center" prop="drugName">
                      <template slot-scope="scope">
                        <image-upload :limit="1" v-model="scope.row.image"/>
                      </template>
                    </el-table-column>
                    <el-table-column label="售价" align="center" prop="drugName">
                      <template slot-scope="scope">
                        <el-input placeholder="0" v-model="scope.row.price"></el-input>
                      </template>
                    </el-table-column>
                    <el-table-column label="成本价" align="center" prop="drugName">
                      <template slot-scope="scope">
                        <el-input placeholder="0" v-model="scope.row.cost"></el-input>
                      </template>
                    </el-table-column>
                    <el-table-column label="原价" align="center" prop="drugName">
                      <template slot-scope="scope">
                        <el-input placeholder="0" v-model="scope.row.otPrice"></el-input>
                      </template>
                    </el-table-column>
                    <el-table-column label="库存" align="center" prop="drugName">
                      <template slot-scope="scope">
                        <el-input placeholder="0" v-model="scope.row.stock"></el-input>
                      </template>
                    </el-table-column>
                    <el-table-column label="产品编号" align="center" prop="drugName">
                      <template slot-scope="scope">
                        <el-input placeholder="产品编号" v-model="scope.row.itemNo"></el-input>
                      </template>
                    </el-table-column>
                    <el-table-column label="重量(KG)" align="center" prop="drugName">
                      <template slot-scope="scope">
                        <el-input placeholder="0" v-model="scope.row.weight"></el-input>
                      </template>
                    </el-table-column>
                    <el-table-column label="体积(m³)" align="center" prop="drugName">
                      <template slot-scope="scope">
                        <el-input placeholder="0" v-model="scope.row.volume"></el-input>
                      </template>
                    </el-table-column>
                    <el-table-column
                      fixed="right"
                      label="操作"
                      width="120">
                      <template slot-scope="scope">
                        <el-button
                          @click.native.prevent="batchAdd"
                          type="text"
                          size="small">
                          批量添加
                        </el-button>
                        <el-button
                          @click.native.prevent="cleanBatchObj"
                          type="text"
                          size="small">
                          清空
                        </el-button>
                      </template>
                    </el-table-column>
                  </el-table-column>
                </el-table>

                <br><br>

                <el-table
                  :data="generateForm.tableData"
                  style="width: 100%"
                  border
                  @selection-change="handleSelectionChange"
                >
                  <el-table-column
                    v-for="(item, index) in generateForm.tableOption"
                    :key="index"
                    :label="item.label"
                    :formatter="item.formatter"
                  >
                  </el-table-column>
                  <el-table-column label="图片" align="center" prop="drugName">
                    <template slot-scope="scope">
                      <image-upload   :on-remove="handleRemove"
                                      :limit="1" v-model="scope.row.image"/>
                    </template>
                  </el-table-column>
                  <el-table-column label="售价" align="center" prop="drugName">
                    <template slot-scope="scope">
                      <el-input placeholder="0" v-model="scope.row.price"></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column label="成本价" align="center" prop="drugName">
                    <template slot-scope="scope">
                      <el-input placeholder="0" v-model="scope.row.cost"></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column label="原价" align="center" prop="drugName">
                    <template slot-scope="scope">
                      <el-input placeholder="0" v-model="scope.row.otPrice"></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column label="库存" align="center" prop="drugName">
                    <template slot-scope="scope">
                      <el-input placeholder="0" v-model="scope.row.stock"></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column label="产品编号" align="center" prop="drugName">
                    <template slot-scope="scope">
                      <el-input placeholder="产品编号" v-model="scope.row.itemNo"></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column label="重量(KG)" align="center" prop="drugName">
                    <template slot-scope="scope">
                      <el-input placeholder="0" v-model="scope.row.weight"></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column label="体积(m³)" align="center" prop="drugName">
                    <template slot-scope="scope">
                      <el-input placeholder="0" v-model="scope.row.volume"></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作">
                    <template slot-scope="scope">
                      <el-button type="text" size="small" @click.native.prevent="deleteRow(scope.$index)">删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </el-form>
          <div class="dialog-footer">
            <el-button @click="toPrev">上一步</el-button>
            <el-button type="primary" @click="toNext">下一步</el-button>
          </div>
        </el-tab-pane>
        <el-tab-pane label="商品详情" name="third">

          <el-form ref="form" :model="form" :rules="rules" label-width="120px">
            <el-form-item label="商品详情">
              <editor v-model="form.details" :min-height="500"/>
            </el-form-item>
          </el-form>
          <div class="dialog-footer">
            <el-button @click="toPrev">上一步</el-button>
            <el-button type="primary" @click="toNext">下一步</el-button>
          </div>
        </el-tab-pane>
        <el-tab-pane v-if="isShowFourth" label="物流设置" name="fourth">
          <el-form ref="form" :model="form" :rules="rules" label-width="120px">

            <el-form-item label="物流方式">
              <el-checkbox v-model="express" disabled>快递</el-checkbox>
              <el-checkbox v-model="form.hexiao">到店核销</el-checkbox>
            </el-form-item>

            <el-form-item label="运费设置">
              <el-radio v-model="fare" :label="0">包邮</el-radio>
              <el-radio v-model="fare" :label="1">运费</el-radio>
            </el-form-item>
            <div v-if="fare === 1">
              <el-form-item label="运费金额">
                <el-input type="number" v-model="form.freightAmount" placeholder="请输入运费金额"/>
              </el-form-item>
            </div>
          </el-form>
          <div class="dialog-footer">
            <el-button @click="toPrev">上一步</el-button>
            <el-button type="primary" @click="toNext">下一步</el-button>
          </div>
        </el-tab-pane>
        <el-tab-pane label="营销设置" name="fifth">
          <el-form ref="form" :model="form" :rules="rules" label-width="120px">

            <el-form-item label="虚拟销量" prop="ficti">
              <el-input type="number" v-model="form.ficti" placeholder="请输入虚拟销量"/>
            </el-form-item>
            <el-form-item label="排序" prop="sort">
              <el-input type="number" v-model="form.sort" placeholder="请输入排序"/>
            </el-form-item>
            <el-form-item label="获得积分" prop="giveIntegral">
              <el-input type="number" v-model="form.giveIntegral" placeholder="请输入获得积分"/>
            </el-form-item>
            <el-form-item label="商品推荐">
              <el-checkbox v-model="form.isHot">热卖单品</el-checkbox>
              <el-checkbox v-model="form.isBenefit">促销单品</el-checkbox>
              <el-checkbox v-model="form.isBest">精品推荐</el-checkbox>
              <el-checkbox v-model="form.isNew">首发新品</el-checkbox>
              <el-checkbox v-model="form.isGood">优品推荐</el-checkbox>
            </el-form-item>
            <el-form-item label="积分购买" prop="jf">
              <el-switch
                v-model="form.jf"
                active-color="#13ce66"
                :active-value="1"
                :inactive-value="0">
              </el-switch>
            </el-form-item>
          </el-form>
          <div class="dialog-footer">
            <el-button @click="toPrev">上一步</el-button>
            <el-button type="primary" @click="toNext">下一步</el-button>
          </div>
        </el-tab-pane>
        <el-tab-pane label="其他设置" name="sixth">
          <el-form ref="form" :model="form" :rules="rules" label-width="120px">
            <el-form-item label="店名" prop="shopName">
              <el-input v-model="form.shopName" placeholder="请输入店名"/>
            </el-form-item>
            <el-form-item label="地址" prop="address">
              <el-input v-model="form.address" placeholder="请输入地址"/>
            </el-form-item>
            <el-form-item label="电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入电话"/>
            </el-form-item>
            <el-form-item label="关键字" prop="keyword">
              <el-input v-model="form.keyword" placeholder="请输入关键字"/>
            </el-form-item>
            <el-form-item label="商品简介" prop="storeInfo">
              <el-input rows="5" type="textarea" v-model="form.storeInfo" placeholder="请输入商品简介"/>
            </el-form-item>
            <el-form-item label="复制口令" prop="commandWord">
              <el-input rows="5" type="textarea" v-model="form.commandWord" placeholder="请输入复制口令"/>
            </el-form-item>

          </el-form>
          <div class="dialog-footer">
            <el-button @click="toPrev">上一步</el-button>
            <el-button type="primary" @click="submitForm">保存</el-button>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>
</template>

<script>
import {listProduct, getProduct , addProduct, updateProduct, delProductUpd} from "@/api/custom/product";
import {listTreeCategory, listSelectCategory} from "@/api/custom/category"
import {listRuleSelect, getRule} from "@/api/custom/rule"

export default {
  name: "Product",
  data() {
    return {
      delTableDataUniqueValueList: [],
      express: true,
      isShowTable: false,
      nullObj: {
        image: null,
        price: null,
        cost: null,
        otPrice: null,
        stock: null,
        itemNo: null,
        weight: null,
        volume: null
      },
      batchObj: [],
      ruleValue: [],
      generateForm: {
        tableOption: [],
        tableData: []
      },
      ruleSelectList: [],
      fare: 0,
      specs: 0,
      videoLinkSwitch: false,
      treeSelectData: [],
      activeName: 'first',
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      treeExpandedId: [],
      treeData: [],
      treeNode: {}, //选中的记录
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品表格数据
      productList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        merId: null,
        image: null,
        recommendImage: null,
        sliderImage: null,
        storeName: null,
        storeInfo: null,
        keyword: null,
        barCode: null,
        cateId: null,
        rule:null,
        price: null,
        vipPrice: null,
        otPrice: null,
        postage: null,
        unitName: null,
        sort: null,
        sales: null,
        stock: null,
        isShow: null,
        fare: 1,
        isHot: null,
        isBenefit: null,
        isBest: null,
        isNew: null,
        isVirtual: null,
        virtualType: null,
        addTime: null,
        isPostage: null,
        isDel: null,
        merUse: null,
        giveIntegral: null,
        cost: null,
        isSeckill: null,
        isBargain: null,
        isGood: null,
        isSub: null,
        isVip: null,
        ficti: null,
        browse: null,
        codePath: null,
        soureLink: null,
        videoLink: null,
        tempId: null,
        specType: null,
        activity: null,
        spu: null,
        labelId: null,
        commandWord: null,
        recommendList: null,
        vipProduct: null,
        presale: null,
        presaleStartTime: null,
        presaleEndTime: null,
        presaleDay: null,
        logistics: null,
        freight: null,
        customForm: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        cateId: [
          {required: true, message: "商品分类不能为空", trigger: "change"}
        ],
        storeName: [
          {required: true, message: "商品名称不能为空", trigger: "blur"}
        ],
        unitName: [
          {required: true, message: "单位名不能为空", trigger: "blur"}
        ],
        cost: [
          {required: true, message: "成本价不能为空", trigger: "blur"}
        ],
        otPrice: [
          {required: true, message: "原价不能为空", trigger: "blur"}
        ],
        price: [
          {required: true, message: "商品售价不能为空", trigger: "blur"}
        ],
        stock: [
          {required: true, message: "库存不能为空", trigger: "blur"}
        ],
        itemNo: [
          {required: true, message: "编号不能为空", trigger: "blur"}
        ],
        giveIntegral: [
          {required: true, message: "获得积分不能为空", trigger: "blur"}
        ],
        sort: [
          {required: true, message: "排序不能为空", trigger: "blur"}
        ],
        ficti: [
          {required: true, message: "虚拟销量不能为空", trigger: "blur"}
        ],
        sliderImage: [
          {required: true, message: "轮播图不能为空", trigger: "blur"}
        ]
      }
    };
  },
  created() {
    this.batchObj.push({...this.nullObj})
    this.getList();
    this.getTreeList();
    this.getRuleSelectList();
  },
  filters:{
    salesSum(arr){
      let sum = 0
      arr.forEach(item => {
        sum += Number(item.sales)
      })
      return sum
    },
    stockSum(arr){
      return arr.reduce((pre,item)=> pre + (item.stock ? Number(item.stock) : 0) ,0)
    }
  },
  watch: {
    specs: {
      deep: true,
      handler(newVal, oldVal) {
        if(newVal === 0 && this.form.id != null){
          this.form.image = null;
          this.form.cost = null;
          this.form.otPrice = null;
          this.form.price = null;
          this.form.stock = null;
          this.form.itemNo = null;
          this.form.weight = null;
          this.form.volume = null;
        }
      },
      immediate: true
    }
  },
  computed: {
    isShowFourth() {
      return this.form.isVirtual === 0
    },
  },
  methods: {
    handleRemove(file, fileList) {
      // console.log(file, fileList);
    },
    selectChange() {
      getRule(this.form.rule).then(response => {
        this.ruleValue = JSON.parse(response.data.ruleValue);
      })
      this.isShowTable = false;
      this.generateForm.tableData = [];
      this.generateForm.tableOption = [];
    },
    addList(specs) {
      this.generateForm.tableData.push({
        specs: specs,
        ...this.nullObj
      })
    },
    // addParamsSetting() {
    //   this.addList()
    // },
    // 删除当前行
    deleteRow(index) {
      if(this.form.id){
        this.delTableDataUniqueValueList.push(this.generateForm.tableData[index].uniqueValue)
      }
      this.generateForm.tableData.splice(index, 1)
    },
    batchAdd() {
      let {tableData} = this.generateForm;
      for (let i = 0; i < tableData.length; i++) {
        let temp = {...this.batchObj[0], specs: this.generateForm.tableData[i].specs ,uniqueValue: this.generateForm.tableData[i].uniqueValue}
        this.generateForm.tableData.splice(i, 1, temp)
      }
    },
    cleanBatchObj() {
      this.batchObj.splice(0, 1, {...this.nullObj})
    },
    toGenerate() {
      let that = this;
      if (!this.form.rule) {
        this.$message({
          message: '请选择规则',
          type: 'warning'
        });
        return false;
      }
      this.isShowTable = true;
      this.generateForm.tableData = [];
      this.generateForm.tableOption = [];
      getRule(this.form.rule).then(response => {
        this.ruleValue = JSON.parse(response.data.ruleValue);
        let {ruleValue} = this;
        this.generateForm.tableOption.push({
          label: '规格',

          formatter: function (row) {
            return row.specs;
          }
        })
        this.deleteRow(0);

        if (ruleValue) {

          let array = []

          for (let i = 0; i < ruleValue.length; i++) {
            array.push(ruleValue[i].value.split(','))
          }

          let arr = [];
          deep(array, 0, arr);

          function deep(array, i, arr) {
            if (array.length > i) {
              i++;
            } else {
              that.addList(arr.join('-'))
              return;
            }
            let tempArr = array[i - 1];
            for (let j = 0; j < tempArr.length; j++) {
              arr.push(tempArr[j]);
              deep(array, i, arr);
              arr.pop();
            }
          }
        }

      })
    },
    getRuleSelectList() {
      listRuleSelect().then(response => {
        this.ruleSelectList = response.rows;
      })
    },
    toPrev() {
      let {activeName} = this;
      if (activeName === 'sixth') {
        this.activeName = 'fifth'
      } else if (activeName === 'fifth' && this.form.isVirtual !== 0) {
        this.activeName = 'third'
      } else if (activeName === 'fifth' && this.form.isVirtual === 0) {
        this.activeName = 'fourth'
      } else if (activeName === 'fourth') {
        this.activeName = 'third'
      } else if (activeName === 'third') {
        this.activeName = 'second'
      } else if (activeName === 'second') {
        this.activeName = 'first'
      }
    },
    toNext() {
      let {activeName} = this;
      if (activeName === 'first') {
        this.activeName = 'second'
      } else if (activeName === 'second') {
        this.activeName = 'third'
      } else if (activeName === 'third' && this.form.isVirtual !== 0) {
        this.activeName = 'fifth'
      } else if (activeName === 'third' && this.form.isVirtual === 0) {
        this.activeName = 'fourth'
      } else if (activeName === 'fourth') {
        this.activeName = 'fifth'
      } else if (activeName === 'fifth') {
        this.activeName = 'sixth'
      }
    },
    handleClick(tab, event) {
      // console.log(tab, event);
    },
    clearOptionTree() {
      this.treeNode = {}
      this.queryParams.cateName = ''
    },
    /*
    * 点击节点
    * */
    handleNodeClick(data) {
      this.treeNode = data // 根据自己的需要，赋值
      this.queryParams.cateName = data.label
      this.$refs.elSelectTable.blur() // 收起下拉列表
    },
    getTreeList() {
      listTreeCategory().then(response => {
        this.treeData = response.data;
      })
      listSelectCategory().then(response => {
        this.treeSelectData = response.data;
      })
    },
    /** 查询商品列表 */
    getList() {
      this.loading = true;
      this.queryParams.isDel = 0;
      listProduct(this.queryParams).then(response => {
        this.productList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        merId: null,
        isVirtual: 0,
        cateId: null,
        storeName: null,
        unitName: null,
        sliderImage: null,
        isShow: null,
        image: null,
        cost: null,
        otPrice: null,
        price: null,
        stock: null,
        itemNo: null,
        weight: null,
        volume: null,
        specs: null,
        express: true,
        hexiao: null,
        fare: null,
        freightAmount: null,
        ficti: null,
        sort: null,
        giveIntegral: null,
        isHot: null,
        isBenefit: null,
        isBest: null,
        isNew: null,
        isGood: null,
        jf: null,
        shopName: null,
        address: null,
        phone: null,
        keyword: null,
        storeInfo: null,
        commandWord: null,
        createTime: null,
        updateTime: null
      };
      this.activeName = 'first'
      this.form.isShow = 0
      this.isShowTable = false;
      this.generateForm.tableData = [];
      this.generateForm.tableOption = [];
      this.delTableDataUniqueValueList = [];
      this.specs = 0
      this.fare = 0
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.queryParams.cateId = this.treeNode.value
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getProduct(id).then(response => {
        this.form = response.data;
        this.specs = this.form.specType;
        this.isShowTable = true;
        this.generateForm.tableData = JSON.parse(this.form.customForm)
        this.form.hexiao = this.form.hexiao !== 0
        this.form.express = this.form.express !== 0
        this.form.isBenefit = this.form.isBenefit !== 0
        this.form.isBest = this.form.isBest !== 0
        this.form.isGood = this.form.isGood !== 0
        this.form.isHot = this.form.isHot !== 0
        this.form.isNew = this.form.isNew !== 0
        this.form.hexiao = this.form.hexiao !== 0
        this.fare = this.form.fare
        this.activeName = 'first'
        this.generateForm.tableOption.push({
          label: '规格',
          formatter: function (row) {
            return row.specs;
          }
        })
        this.open = true;
        this.title = "修改商品";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // this.form.specs = this.specs;
          this.form.specType = this.specs;
          this.form.fare = this.fare;
          if(this.specs === 0){
            this.form.tableData = []
            this.form.tableData.push({
              image: this.image,
              price: this.price,
              cost: this.cost,
              otPrice: this.otPrice,
              stock: this.stock,
              itemNo: this.itemNo,
              weight: this.weight,
              volume: this.volume
            })
          }else {
            this.form.image = this.generateForm.tableData[0].image
            this.form.tableData = this.generateForm.tableData;
          }
          this.form.tableData = JSON.stringify(this.form.tableData)
          this.form.express = this.form.express ? 1 : 0;
          this.form.isBenefit = this.form.isBenefit ? 1 : 0;
          this.form.isBest = this.form.isBest ? 1 : 0;
          this.form.isGood = this.form.isGood ? 1 : 0;
          this.form.isHot = this.form.isHot ? 1 : 0;
          this.form.isNew = this.form.isNew ? 1 : 0;
          this.form.hexiao = this.form.hexiao ? 1 : 0;
          this.form.delTableDataUniqueValueList = JSON.stringify(this.delTableDataUniqueValueList);

          if (this.form.id != null) {
            updateProduct(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProduct(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除商品编号为"' + ids + '"的数据项？').then(function () {
        return delProductUpd(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('custom/product/export', {
        ...this.queryParams
      }, `product_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style>
.selectOptionTree {
  height: auto;
  background: white;
  padding: 0;
}

.selectOptionTree:hover {
  background: white;
}

.el-radio-group .el-radio__input {
  display: none;
}

.el-radio-group label {
  margin: auto;
}

.dialog-footer {
  margin: 10px 35%;
}

.img-uploader {
  height: 37px;
  width: 50px;
}

.cell {
  text-align: center;
}

.el-upload--picture-card {
  width: 35px;
  height: 35px;
}

.el-upload-list--picture-card .el-upload-list__item {
  width: 35px;
  height: 35px;
}

.el-icon-plus {
  display: none;
}

.tag1 {
  margin-left: -7%;
}
</style>
